package com.xiaodu.acer.phoneplay.ui.activity;

import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.mikepenz.iconics.IconicsDrawable;
import com.mikepenz.ionicons_typeface_library.Ionicons;
import com.orhanobut.logger.Logger;
import com.xiaodu.acer.phoneplay.R;
import com.xiaodu.acer.phoneplay.bean.AppInfo;
import com.xiaodu.acer.phoneplay.bean.SearchHistoryBean;
import com.xiaodu.acer.phoneplay.bean.SearchResult;
import com.xiaodu.acer.phoneplay.common.rx.subscriber.RxSchedulers;
import com.xiaodu.acer.phoneplay.di.component.AppComponent;
import com.xiaodu.acer.phoneplay.di.component.DaggerSearchComponent;
import com.xiaodu.acer.phoneplay.di.module.SearchModule;
import com.xiaodu.acer.phoneplay.presenter.SearchPresenter;
import com.xiaodu.acer.phoneplay.presenter.contract.SearchContract;
import com.xiaodu.acer.phoneplay.ui.adapter.AppInfoAdapter;
import com.xiaodu.acer.phoneplay.ui.adapter.SearchHistoryAdatper;
import com.xiaodu.acer.phoneplay.ui.adapter.SuggestionAdapter;
import com.xiaodu.acer.phoneplay.ui.base.BaseActivity;
import com.xiaodu.acer.phoneplay.ui.decoration.DividerItemDecoration;
import com.xiaodu.acer.phoneplay.ui.decoration.SpaceItemDecoration2;

import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Predicate;
import retrofit2.Retrofit;

public class SearchActivity extends BaseActivity<SearchPresenter>
        implements SearchContract.View {

    @BindView(R.id.searchTextView)
    EditText mSearchTextView;
    @BindView(R.id.action_clear_btn)
    ImageView mActionClearBtn;
    @BindView(R.id.search_bar)
    RelativeLayout mSearchBar;
    @BindView(R.id.toolbar)
    Toolbar search_toolBar;
    @BindView(R.id.btn_clear)
    ImageView mBtnClear;
    @BindView(R.id.recycler_view_history)
    RecyclerView mRecyclerViewHistory;
    @BindView(R.id.layout_history)
    LinearLayout mLayoutHistory;
    @BindView(R.id.recycler_view_suggestion)
    RecyclerView mRecyclerViewSuggestion;
    @BindView(R.id.recycler_view_result)
    RecyclerView mRecyclerViewResult;
    @BindView(R.id.activity_search)
    LinearLayout mActivitySearch;


    private SuggestionAdapter mSuggestionAdapter;
    private AppInfoAdapter mAppInfoAdapter;
    private SearchHistoryAdatper mSearchHistoryAdatper;


    @Inject
    Retrofit mRetrofit;

    @Override
    public int setLayout() {
        return R.layout.activity_search;
    }

    @Override
    public void setupAcitivtyComponent(AppComponent appComponent) {
        DaggerSearchComponent.builder()
                .appComponent(appComponent)
                .searchModule(new SearchModule(this))
                .build()
                .inject(this);
    }

    @Override
    public void initView() {
        //刚进去先展示历史搜索
        mPresenter.showHistory();
        //隐藏baseToolBar
        mToolBar.setVisibility(View.GONE);
        search_toolBar.setNavigationIcon(
                new IconicsDrawable(this)
                        .icon(Ionicons.Icon.ion_ios_arrow_back)
                        .sizeDp(14)
                        .color(getResources().getColor(R.color.md_white_1000)
                        )
        );

        mActionClearBtn.setImageDrawable(new IconicsDrawable(this, Ionicons.Icon.ion_ios_close_empty)
                .color(ContextCompat.getColor(this, R.color.white)).sizeDp(14));

        mBtnClear.setImageDrawable(new IconicsDrawable(this, Ionicons.Icon.ion_ios_trash_outline)
                .color(ContextCompat.getColor(this, R.color.md_grey_600)).sizeDp(14));


        setupSuggestionRecycleView();
        initSearchResultRecycleView();

    }

    @Override
    public void initData() {

    }

    @Override
    public void initListener() {
        search_toolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        //清空历史记录的点击事件
        RxView.clicks(mBtnClear)
                .throttleFirst(3, TimeUnit.SECONDS)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        mPresenter.deleteHistory();
                    }
                });

        //清空搜索栏的内容
        RxView.clicks(mActionClearBtn)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(@NonNull Object o) {
                        try {
                            Logger.e("mActionClearBtn");
                            mSearchTextView.setText("");
                            //显示历史记录，同时隐藏
                            mLayoutHistory.setVisibility(View.VISIBLE);

                            mRecyclerViewSuggestion.setVisibility(View.GONE);
                            mRecyclerViewResult.setVisibility(View.GONE);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                });

        RxTextView.editorActions(mSearchTextView).subscribe(new Consumer<Integer>() {
            @Override
            public void accept(@NonNull Integer integer) {
                try {
                    Logger.e("mActionClearBtn");
                    search(mSearchTextView.getText().toString().trim());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        RxTextView.textChanges(mSearchTextView)
                .debounce(100, TimeUnit.MILLISECONDS)
                .compose(RxSchedulers.<CharSequence>io_main())
                .filter(new Predicate<CharSequence>() {
                    @Override
                    public boolean test(@NonNull CharSequence charSequence) throws Exception {
                        return charSequence.toString().trim().length() > 0;
                    }
                })
                .subscribe(new Consumer<CharSequence>() {
                    @Override
                    public void accept(@NonNull CharSequence charSequence) throws Exception {
                        try {
                            Logger.e(charSequence.toString().trim());
                            if (charSequence.length() > 0) {
                                mActionClearBtn.setVisibility(View.VISIBLE);
                            } else {
                                mActionClearBtn.setVisibility(View.GONE);
                            }
                            mPresenter.saveSearchHistory(charSequence.toString().trim());
                            mPresenter.getSuggestion(charSequence.toString().trim());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }


                    }
                });


    }

    private void search(String keyword) {
        mPresenter.search(keyword);
    }

    //初始化SuggestionRecycleView
    private void setupSuggestionRecycleView() {
        mSuggestionAdapter = new SuggestionAdapter();

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);

        mRecyclerViewSuggestion.setLayoutManager(layoutManager);
        DividerItemDecoration itemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST);
        mRecyclerViewSuggestion.addItemDecoration(itemDecoration);
        mRecyclerViewSuggestion.setAdapter(mSuggestionAdapter);

        mRecyclerViewSuggestion.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                search(mSuggestionAdapter.getItem(position));
            }
        });

    }


    private void initSearchResultRecycleView() {
        mAppInfoAdapter = AppInfoAdapter.builder()
                .showBrief(false)
                .showCategoryName(true)
              //  .rxDownload(mRxDownload)
                .retrofit(mRetrofit)
                .build();

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        mRecyclerViewResult.setLayoutManager(layoutManager);

        DividerItemDecoration itemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST);
        mRecyclerViewResult.addItemDecoration(itemDecoration);

        mRecyclerViewResult.setAdapter(mAppInfoAdapter);

        mRecyclerViewResult.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                AppInfo appInfo = mAppInfoAdapter.getItem(position);
                mApplication.setView(view);
                Intent intent = new Intent(
                        SearchActivity.this, AppDetailActivity.class);
                intent.putExtra("appinfo", appInfo);
                startActivity(intent);
            }
        });

    }

    private void initHistoryRecycleView(final List<SearchHistoryBean> list) {
        mSearchHistoryAdatper = new SearchHistoryAdatper();
        mSearchHistoryAdatper.addData(list);

        RecyclerView.LayoutManager lm = new GridLayoutManager(this, 5);
        SpaceItemDecoration2 itemd = new SpaceItemDecoration2(10);
        mRecyclerViewHistory.addItemDecoration(itemd);

        mRecyclerViewHistory.setLayoutManager(lm);
        mRecyclerViewHistory.setAdapter(mSearchHistoryAdatper);

        mRecyclerViewHistory.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                mSearchTextView.setText(list.get(position).getName());
                search(mSearchHistoryAdatper.getItem(position).getName());
            }
        });
    }


    @Override
    public void showSearchHistory(List<SearchHistoryBean> list) {
        Logger.e("showSearchHistory");
        initHistoryRecycleView(list);

        mLayoutHistory.setVisibility(View.VISIBLE);

        mRecyclerViewSuggestion.setVisibility(View.GONE);
        mRecyclerViewResult.setVisibility(View.GONE);
    }

    @Override
    public void showSuggestions(List<String> list) {
        Logger.e("showSuggestions");
        mSuggestionAdapter.setNewData(list);

        mRecyclerViewSuggestion.setVisibility(View.VISIBLE);

        mLayoutHistory.setVisibility(View.GONE);
        mRecyclerViewResult.setVisibility(View.GONE);
    }

    @Override
    public void showSearchResult(SearchResult result) {
        Logger.e("showSearchResult");
        mAppInfoAdapter.setNewData(result.getListApp());
        mRecyclerViewSuggestion.setVisibility(View.GONE);
        mLayoutHistory.setVisibility(View.GONE);
        mRecyclerViewResult.setVisibility(View.VISIBLE);
    }

    @Override
    public void deleteSearchHistory() {
        //清空数据
        mSearchHistoryAdatper.setNewData(null);
    }


}
